import { UserProfile } from '../../auth/types';

const API_BASE = '/api';

export interface TorrentUploadResponse {
  success: boolean;
  message: string;
  points?: number;
}

export interface TorrentInfo {
  id: string;
  name: string;
  size: number;
  uploaderId: string;
  uploaderName: string;
  createdAt: string;
  downloadCount: number;
  seeders: number;
  leechers: number;
}

export interface TorrentListResponse {
  torrents: TorrentInfo[];
  total: number;
  page: number;
  pageSize: number;
}

export class TorrentService {
  private static getHeaders(includeAuth: boolean = true) {
    const headers: Record<string, string> = {
      'Accept': 'application/json',
    };

    if (includeAuth) {
      const token = localStorage.getItem('token');
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
    }

    return headers;
  }

  static async uploadTorrent(file: File, userId: string): Promise<TorrentUploadResponse> {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('userId', userId);

    const response = await fetch(`${API_BASE}/torrents/upload`, {
      method: 'POST',
      headers: this.getHeaders(true),
      body: formData
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '上传失败');
    }

    return response.json();
  }

  static async downloadTorrent(torrentId: string): Promise<Blob> {
    const response = await fetch(`${API_BASE}/torrents/${torrentId}/download`, {
      method: 'GET',
      headers: this.getHeaders(true)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '下载失败');
    }

    return response.blob();
  }

  static async getTorrentList(page: number = 1, pageSize: number = 10): Promise<TorrentListResponse> {
    const response = await fetch(`${API_BASE}/torrents?page=${page}&pageSize=${pageSize}`, {
      method: 'GET',
      headers: this.getHeaders(true)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '获取种子列表失败');
    }

    return response.json();
  }

  static async deleteTorrent(torrentId: string): Promise<void> {
    const response = await fetch(`${API_BASE}/torrents/${torrentId}`, {
      method: 'DELETE',
      headers: this.getHeaders(true)
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || '删除种子失败');
    }
  }
}